import React, { Component } from 'react'
import { Menu } from 'antd'
import { MenuWrapper } from './style'
import { HomeOutlined, UserOutlined, FormOutlined } from '@ant-design/icons'
import { withRouter } from 'react-router-dom'

class LeftMenu extends Component {
  state = {
    openKeys: [],
    selectedKeys: []
  }

  componentDidMount() {
    const { pathname } = this.props.history.location
    this.setState({
      selectedKeys: [pathname]
    })
  }

  clickMenu = (obj) => {
    this.props.history.push(obj.key)
    this.setState({
      selectedKeys: [obj.key]
    })
  }

  changeSubMenu = (keys) => {
    const { openKeys } = this.state
    const latestKey = keys.find((k) => openKeys.indexOf(k) === -1)
    if (latestKey) {
      this.setState({
        openKeys: [latestKey]
      })
    } else {
      this.setState({
        openKeys: keys
      })
    }
  }

  render() {
    const { openKeys, selectedKeys } = this.state
    return (
      <MenuWrapper width={250}>
        <div className="logo">
          <div className="logo-img"></div>
          <div className="logo-text"></div>
        </div>
        <Menu
          mode="inline"
          theme="dark"
          selectedKeys={selectedKeys}
          openKeys={openKeys}
          onClick={this.clickMenu}
          onOpenChange={this.changeSubMenu}
        >
          <Menu.Item key="/" icon={<HomeOutlined />}>
            首页
          </Menu.Item>
          <Menu.SubMenu key="/auth" title="权限管理" icon={<UserOutlined />}>
            <Menu.Item key="/auth/resources">权限资源</Menu.Item>
            <Menu.Item key="/auth/roles">角色管理</Menu.Item>
            <Menu.Item key="/auth/users">用户列表</Menu.Item>
          </Menu.SubMenu>
          <Menu.SubMenu key="3" title="博客管理" icon={<FormOutlined />}>
            <Menu.Item key="3-1">整体概览</Menu.Item>
            <Menu.Item key="3-2">文章列表</Menu.Item>
            <Menu.Item key="3-3">编辑文章</Menu.Item>
          </Menu.SubMenu>
        </Menu>
      </MenuWrapper>
    )
  }
}

export default withRouter(LeftMenu)
